<template>
  <div class="post-loan-assessment">
    <el-card>
      <template #header>
        <div class="card-header">
          <h3>贷后评估</h3>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddAssessment">新增评估</el-button>
            <el-button type="success" @click="handleExport">导出</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="贷款编号">
          <el-input v-model="searchForm.loanNo" placeholder="请输入贷款编号" clearable></el-input>
        </el-form-item>
        <el-form-item label="客户名称">
          <el-input v-model="searchForm.customerName" placeholder="请输入客户名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="评估类型">
          <el-select v-model="searchForm.type" placeholder="请选择评估类型" clearable>
            <el-option label="定期评估" value="regular"></el-option>
            <el-option label="临时评估" value="temporary"></el-option>
            <el-option label="到期评估" value="maturity"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评估时间">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 数据表格 -->
      <el-table :data="tableData" border style="width: 100%" v-loading="loading">
        <el-table-column prop="loanNo" label="贷款编号" width="180"></el-table-column>
        <el-table-column prop="customerName" label="客户名称" width="120"></el-table-column>
        <el-table-column prop="assessmentDate" label="评估日期" width="120"></el-table-column>
        <el-table-column prop="assessor" label="评估人员" width="120"></el-table-column>
        <el-table-column prop="type" label="评估类型" width="120">
          <template #default="scope">
            {{ getAssessmentType(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="score" label="评估得分" width="100">
          <template #default="scope">
            <el-tag :type="getScoreType(scope.row.score)">{{ scope.row.score }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="rating" label="评估等级" width="100">
          <template #default="scope">
            <el-tag :type="getRatingType(scope.row.rating)">{{ getRatingText(scope.row.rating) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="scope">
            <el-button link type="primary" @click="handleView(scope.row)">查看</el-button>
            <el-button link type="primary" @click="handleEdit(scope.row)" :disabled="scope.row.status === 'completed'">编辑</el-button>
            <el-button link type="primary" @click="handleDelete(scope.row)" :disabled="scope.row.status === 'completed'">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑评估对话框 -->
    <el-dialog 
      v-model="assessmentDialogVisible" 
      :title="assessmentForm.id ? '编辑评估' : '新增评估'"
      width="800px"
    >
      <el-form :model="assessmentForm" label-width="120px" :rules="assessmentRules" ref="assessmentFormRef">
        <el-form-item label="贷款编号" prop="loanNo">
          <el-select v-model="assessmentForm.loanNo" placeholder="请选择贷款" filterable style="width: 100%">
            <el-option
              v-for="item in loanOptions"
              :key="item.loanNo"
              :label="`${item.loanNo} - ${item.customerName}`"
              :value="item.loanNo"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评估类型" prop="type">
          <el-select v-model="assessmentForm.type" placeholder="请选择评估类型" style="width: 100%">
            <el-option label="定期评估" value="regular"></el-option>
            <el-option label="临时评估" value="temporary"></el-option>
            <el-option label="到期评估" value="maturity"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评估日期" prop="assessmentDate">
          <el-date-picker v-model="assessmentForm.assessmentDate" type="date" placeholder="选择评估日期" style="width: 100%"></el-date-picker>
        </el-form-item>
        <el-form-item label="评估人员" prop="assessor">
          <el-select v-model="assessmentForm.assessor" placeholder="请选择评估人员" style="width: 100%">
            <el-option
              v-for="item in assessorOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>

        <!-- 评估指标 -->
        <el-divider>评估指标</el-divider>
        
        <el-form-item label="经营情况" prop="businessScore">
          <el-rate
            v-model="assessmentForm.businessScore"
            :max="5"
            :texts="['极差', '较差', '一般', '良好', '优秀']"
            show-text
          ></el-rate>
        </el-form-item>
        <el-form-item label="财务状况" prop="financialScore">
          <el-rate
            v-model="assessmentForm.financialScore"
            :max="5"
            :texts="['极差', '较差', '一般', '良好', '优秀']"
            show-text
          ></el-rate>
        </el-form-item>
        <el-form-item label="还款能力" prop="repaymentScore">
          <el-rate
            v-model="assessmentForm.repaymentScore"
            :max="5"
            :texts="['极差', '较差', '一般', '良好', '优秀']"
            show-text
          ></el-rate>
        </el-form-item>
        <el-form-item label="担保情况" prop="guaranteeScore">
          <el-rate
            v-model="assessmentForm.guaranteeScore"
            :max="5"
            :texts="['极差', '较差', '一般', '良好', '优秀']"
            show-text
          ></el-rate>
        </el-form-item>
        <el-form-item label="管理水平" prop="managementScore">
          <el-rate
            v-model="assessmentForm.managementScore"
            :max="5"
            :texts="['极差', '较差', '一般', '良好', '优秀']"
            show-text
          ></el-rate>
        </el-form-item>

        <el-divider>评估结论</el-divider>

        <el-form-item label="评估得分">
          <el-input v-model="totalScore" disabled>
            <template #append>分</template>
          </el-input>
        </el-form-item>
        <el-form-item label="评估等级">
          <el-tag :type="getRatingType(assessmentRating)">{{ getRatingText(assessmentRating) }}</el-tag>
        </el-form-item>
        <el-form-item label="评估结论" prop="conclusion">
          <el-input v-model="assessmentForm.conclusion" type="textarea" rows="3" placeholder="请输入评估结论"></el-input>
        </el-form-item>
        <el-form-item label="建议措施" prop="suggestions">
          <el-input v-model="assessmentForm.suggestions" type="textarea" rows="3" placeholder="请输入建议措施"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assessmentDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitAssessment">确认</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 查看评估报告对话框 -->
    <el-dialog v-model="viewDialogVisible" title="评估报告" width="800px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="贷款编号">{{ currentAssessment.loanNo }}</el-descriptions-item>
        <el-descriptions-item label="客户名称">{{ currentAssessment.customerName }}</el-descriptions-item>
        <el-descriptions-item label="评估类型">{{ getAssessmentType(currentAssessment.type) }}</el-descriptions-item>
        <el-descriptions-item label="评估日期">{{ currentAssessment.assessmentDate }}</el-descriptions-item>
        <el-descriptions-item label="评估人员">{{ currentAssessment.assessor }}</el-descriptions-item>
        <el-descriptions-item label="评估得分">
          <el-tag :type="getScoreType(currentAssessment.score)">{{ currentAssessment.score }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="评估等级">
          <el-tag :type="getRatingType(currentAssessment.rating)">{{ getRatingText(currentAssessment.rating) }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="状态">
          <el-tag :type="getStatusType(currentAssessment.status)">{{ getStatusText(currentAssessment.status) }}</el-tag>
        </el-descriptions-item>
      </el-descriptions>

      <el-divider>评估指标</el-divider>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="经营情况">
          <el-rate v-model="currentAssessment.businessScore" disabled show-score></el-rate>
        </el-descriptions-item>
        <el-descriptions-item label="财务状况">
          <el-rate v-model="currentAssessment.financialScore" disabled show-score></el-rate>
        </el-descriptions-item>
        <el-descriptions-item label="还款能力">
          <el-rate v-model="currentAssessment.repaymentScore" disabled show-score></el-rate>
        </el-descriptions-item>
        <el-descriptions-item label="担保情况">
          <el-rate v-model="currentAssessment.guaranteeScore" disabled show-score></el-rate>
        </el-descriptions-item>
        <el-descriptions-item label="管理水平" :span="2">
          <el-rate v-model="currentAssessment.managementScore" disabled show-score></el-rate>
        </el-descriptions-item>
        <el-descriptions-item label="评估结论" :span="2">{{ currentAssessment.conclusion }}</el-descriptions-item>
        <el-descriptions-item label="建议措施" :span="2">{{ currentAssessment.suggestions }}</el-descriptions-item>
      </el-descriptions>

      <div class="assessment-attachments" v-if="currentAssessment.attachments && currentAssessment.attachments.length">
        <el-divider>附件资料</el-divider>
        <el-table :data="currentAssessment.attachments" border style="width: 100%">
          <el-table-column prop="name" label="文件名称"></el-table-column>
          <el-table-column prop="size" label="文件大小" width="120"></el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" width="180"></el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="scope">
              <el-button link type="primary" @click="downloadAttachment(scope.row)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { postloanAssessmentApi } from '@/api/postloan'

// 表格数据
const loading = ref(false)
const tableData = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索表单
const searchForm = reactive({
  loanNo: '',
  customerName: '',
  type: '',
  assessmentResult: '',
  dateRange: []
})

// 评估表单
const assessmentDialogVisible = ref(false)
const assessmentFormRef = ref(null)
const assessmentForm = reactive({
  id: '',
  loanNo: '',
  type: '',
  assessmentDate: '',
  assessor: '',
  businessScore: 0,
  financialScore: 0,
  repaymentScore: 0,
  guaranteeScore: 0,
  managementScore: 0,
  conclusion: '',
  suggestions: ''
})

// 表单校验规则
const assessmentRules = {
  loanNo: [{ required: true, message: '请选择贷款', trigger: 'change' }],
  type: [{ required: true, message: '请选择评估类型', trigger: 'change' }],
  assessmentDate: [{ required: true, message: '请选择评估日期', trigger: 'change' }],
  assessor: [{ required: true, message: '请选择评估人员', trigger: 'change' }],
  conclusion: [{ required: true, message: '请输入评估结论', trigger: 'blur' }],
  suggestions: [{ required: true, message: '请输入建议措施', trigger: 'blur' }]
}

// 贷款选项
const loanOptions = ref([])

// 评估人员选项
const assessorOptions = ref([])

// 查看对话框
const viewDialogVisible = ref(false)
const currentAssessment = ref({})

// 计算总分
const totalScore = computed(() => {
  const scores = [
    assessmentForm.businessScore,
    assessmentForm.financialScore,
    assessmentForm.repaymentScore,
    assessmentForm.guaranteeScore,
    assessmentForm.managementScore
  ]
  return (scores.reduce((sum, score) => sum + score, 0) * 20).toFixed(1)
})

// 计算评估等级
const assessmentRating = computed(() => {
  const score = parseFloat(totalScore.value)
  if (score >= 90) return 'A'
  if (score >= 80) return 'B'
  if (score >= 70) return 'C'
  if (score >= 60) return 'D'
  return 'E'
})

// 获取评估类型文本
const getAssessmentType = (type) => {
  const types = {
    regular: '定期评估',
    temporary: '临时评估',
    maturity: '到期评估'
  }
  return types[type] || '未知'
}

// 获取得分类型
const getScoreType = (score) => {
  const scoreNum = parseFloat(score)
  if (scoreNum >= 90) return 'success'
  if (scoreNum >= 80) return 'primary'
  if (scoreNum >= 70) return 'warning'
  return 'danger'
}

// 获取等级类型
const getRatingType = (rating) => {
  const types = {
    A: 'success',
    B: 'primary',
    C: 'warning',
    D: 'danger',
    E: 'danger'
  }
  return types[rating] || 'info'
}

// 获取等级文本
const getRatingText = (rating) => {
  const texts = {
    A: '优秀',
    B: '良好',
    C: '一般',
    D: '较差',
    E: '极差'
  }
  return texts[rating] || '未知'
}

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    draft: 'info',
    processing: 'warning',
    completed: 'success'
  }
  return types[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    draft: '草稿',
    processing: '评估中',
    completed: '已完成'
  }
  return texts[status] || '未知'
}

// 获取数据
const fetchData = () => {
  loading.value = true
  
  const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
    loanNo: searchForm.loanNo,
    customerName: searchForm.customerName,
    type: searchForm.type,
    assessmentResult: searchForm.assessmentResult,
    startDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[0] : '',
    endDate: searchForm.dateRange && searchForm.dateRange.length > 0 ? searchForm.dateRange[1] : ''
  }
  
  postloanAssessmentApi.getList(params).then(res => {
    tableData.value = res.data.rows
    total.value = res.data.total
      loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 获取贷款选项
const fetchLoanOptions = () => {
  // 模拟API调用
  setTimeout(() => {
    loanOptions.value = Array.from({ length: 10 }, (_, index) => ({
      loanNo: `LOAN${String(2023000 + index + 1).padStart(7, '0')}`,
      customerName: `客户${index + 1}`
    }))
  }, 300)
}

// 获取评估人员选项
const fetchAssessorOptions = () => {
  // 模拟API调用
  setTimeout(() => {
    assessorOptions.value = Array.from({ length: 5 }, (_, index) => ({
      id: index + 1,
      name: `评估员${index + 1}`
    }))
  }, 300)
}

// 新增评估
const handleAddAssessment = () => {
  assessmentForm.id = ''
  assessmentForm.loanNo = ''
  assessmentForm.type = ''
  assessmentForm.assessmentDate = ''
  assessmentForm.assessor = ''
  assessmentForm.businessScore = 0
  assessmentForm.financialScore = 0
  assessmentForm.repaymentScore = 0
  assessmentForm.guaranteeScore = 0
  assessmentForm.managementScore = 0
  assessmentForm.conclusion = ''
  assessmentForm.suggestions = ''
  
  assessmentDialogVisible.value = true
  fetchLoanOptions()
  fetchAssessorOptions()
}

// 编辑评估
const handleEdit = (row) => {
  Object.assign(assessmentForm, row)
  assessmentDialogVisible.value = true
  fetchLoanOptions()
  fetchAssessorOptions()
}

// 提交评估
const submitAssessment = () => {
  assessmentFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true
      
      const formData = {
        loanNo: assessmentForm.loanNo,
        assessmentDate: assessmentForm.assessmentDate,
        assessor: assessmentForm.assessor,
        type: assessmentForm.type,
        businessScore: assessmentForm.businessScore,
        financialScore: assessmentForm.financialScore,
        repaymentScore: assessmentForm.repaymentScore,
        guaranteeScore: assessmentForm.guaranteeScore,
        managementScore: assessmentForm.managementScore,
        conclusion: assessmentForm.conclusion,
        suggestions: assessmentForm.suggestions
      }
      
      if (assessmentForm.id) {
        // 更新
        postloanAssessmentApi.update({
          id: assessmentForm.id,
          ...formData
        }).then(() => {
          ElMessage.success('更新成功')
          assessmentDialogVisible.value = false
          fetchData()
        }).finally(() => {
          loading.value = false
        })
      } else {
        // 新增
        postloanAssessmentApi.add(formData).then(() => {
          ElMessage.success('添加成功')
    assessmentDialogVisible.value = false
    fetchData()
        }).finally(() => {
          loading.value = false
        })
  }
    }
  })
}

// 删除评估
const handleDelete = (row) => {
  ElMessageBox.confirm('确认要删除该评估记录吗?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    loading.value = true
    postloanAssessmentApi.delete(row.id).then(() => {
    ElMessage.success('删除成功')
    fetchData()
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {})
}

// 查看评估报告
const handleView = (row) => {
  loading.value = true
  postloanAssessmentApi.getDetail(row.id).then(res => {
    const detail = res.data
  currentAssessment.value = {
    ...row,
      businessScore: detail.businessScore,
      financialScore: detail.financialScore,
      repaymentScore: detail.repaymentScore,
      guaranteeScore: detail.guaranteeScore,
      managementScore: detail.managementScore,
      conclusion: detail.conclusion,
      suggestions: detail.suggestions,
      attachments: detail.attachments
  }
  viewDialogVisible.value = true
    loading.value = false
  }).catch(() => {
    loading.value = false
  })
}

// 下载附件
const downloadAttachment = (file) => {
  ElMessage.success(`开始下载文件：${file.name}`)
}

// 导出
const handleExport = () => {
  ElMessage.success('导出成功')
}

// 分页大小变化
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchData()
}

// 当前页变化
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchData()
}

// 组件挂载时获取数据
onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.post-loan-assessment {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.assessment-attachments {
  margin-top: 20px;
}
</style> 